package com.yuanjing.xiangqinxiangai.view


import android.content.Context
import android.view.TextureView
import android.view.View
import android.widget.FrameLayout
import androidx.core.view.isVisible
import com.blankj.utilcode.util.AppUtils
import com.google.gson.Gson
import com.yuanjing.xiangqinxiangai.liveMessagePlugin
import com.yuanjing.xiangqinxiangai.model.RoomDataModel
import com.yuanjing.xiangqinxiangai.util.LiveEngineUtil
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.common.BasicMessageChannel
import im.zego.zegoexpress.ZegoExpressEngine
import im.zego.zegoexpress.constants.ZegoStreamResourceMode
import im.zego.zegoexpress.constants.ZegoVideoMirrorMode
import im.zego.zegoexpress.entity.ZegoCanvas
import im.zego.zegoexpress.entity.ZegoVideoConfig
import im.zego.zegoexpress.constants.ZegoViewMode
import im.zego.zegoexpress.entity.ZegoPlayerConfig

class LivePreviewView(var context: Context, viewId: Int, args: Any?, messenger: BinaryMessenger) :
    PlatformView {

    private val textureViewParent = FrameLayout(context)
    val textureView: TextureView
        get() {
            if (textureViewParent.childCount == 1) {
                val view = textureViewParent.getChildAt(0)
                if (view is TextureView) {
                    return view
                }
            }
            textureViewParent.removeAllViews()
            val textureView = TextureView(context)
            textureViewParent.addView(textureView, -1, -1)
            textureViewParent.isVisible = true
            return textureView
        }

    lateinit var roomMais: RoomDataModel.RoomMai
    private val messageChannel =
        BasicMessageChannel(messenger, "LivePreviewView_$viewId", StandardMessageCodec.INSTANCE)

    init {
        if (args is Map<*, *>) {
            val roomMaisJson = args["roomMais"]!!.toString()
            roomMais = Gson().fromJson(roomMaisJson, RoomDataModel.RoomMai::class.java)
        }
        // 设置视图管理
        liveMessagePlugin?.livePreviewMap?.put(roomMais.maiIndex, this)
    }

    val streamID: String?
        get() {
            if (roomMais.status == 0) return ""
            if (!roomMais.inputStreamId.isNullOrEmpty()) return roomMais.inputStreamId
            if (!roomMais.outputStreamId.isNullOrEmpty()) return roomMais.outputStreamId
            return ""
        }

    override fun getView(): View {
        return textureViewParent
    }

    override fun dispose() {
        // 释放资源，停止直播等
        LiveEngineUtil.engine.stopPublishingStream()
        LiveEngineUtil.engine.stopPreview()
        liveMessagePlugin?.livePreviewMap?.put(roomMais.maiIndex, null)

    }

    // 开始预览流
    fun startPreview() {
//        val isVideo = roomMais.soundMai == 0
        val isVideo = true
        if (roomMais.isAnchor() && roomMais.status != 0) {
            val open = if (AppUtils.isAppForeground()) roomMais.maiOpen == 0 else true
            LiveEngineUtil.engine.muteMicrophone(open)
            val zegoCanvas = ZegoCanvas(textureView)
            zegoCanvas.viewMode = ZegoViewMode.ASPECT_FILL
            LiveEngineUtil.engine.enableCamera(isVideo)
            if (isVideo) {
                LiveEngineUtil.engine.startPreview(zegoCanvas)
//                LiveViewModel.liveVM?.activity?.liveRoomUtil?.mFaceUnityDataFactory?.bindCurrentRenderer()
            }
            LiveEngineUtil.engine.setVideoMirrorMode(ZegoVideoMirrorMode.BOTH_MIRROR)
            LiveEngineUtil.engine.startPublishingStream(roomMais.inputStreamId)
            LiveEngineUtil.engine.setCaptureVolume(180)
            LiveEngineUtil.engine.mutePublishStreamVideo(!AppUtils.isAppForeground())

            LiveEngineUtil.engine.stopPlayingStream(roomMais.outputStreamId)
        } else {
            val playCanvas = ZegoCanvas(textureView)
            playCanvas.viewMode = ZegoViewMode.ASPECT_FILL
            val playerConfig = ZegoPlayerConfig()
            playerConfig.resourceMode = ZegoStreamResourceMode.ONLY_L3
            LiveEngineUtil.engine.startPlayingStream(
                roomMais.outputStreamId, playCanvas, playerConfig
            )
        }
    }

    // 设置视频配置
    private fun publishSetting() {
        LiveEngineUtil.engine.enableCamera(true)

        val videoConfig = ZegoVideoConfig().apply {
        }

        val videoMirrorMode = ZegoVideoMirrorMode.ONLY_PREVIEW_MIRROR
        LiveEngineUtil.engine.setVideoMirrorMode(videoMirrorMode)

        // 根据房间的麦位数来调整视频配置
        val liumav = when {
            liveMessagePlugin?.roomInfo?.roomMais?.size == 3 -> liveMessagePlugin?.appConfig?.liuMaVO3
            liveMessagePlugin?.roomInfo?.roomMais?.size == 7 -> liveMessagePlugin?.appConfig?.liuMaVO7
            liveMessagePlugin?.roomInfo?.roomMais?.size == 9 -> liveMessagePlugin?.appConfig?.liuMaVO9
            else -> null
        }

        liumav?.let {
            videoConfig.fps = it.frameRate?.toInt() ?: 15
            videoConfig.bitrate = it.codeRate?.toInt() ?: 400
            videoConfig.encodeWidth = it.width?.toInt() ?: 180
            videoConfig.captureWidth = it.width?.toInt() ?: 180
            videoConfig.encodeHeight = it.length?.toInt() ?: 180
            videoConfig.captureHeight = it.length?.toInt() ?: 180
        }

        LiveEngineUtil.engine.setVideoConfig(videoConfig)
    }
}

// Factory 类，用于创建 LivePreviewView
class LivePreviewViewFactory(private val messenger: BinaryMessenger) :
    PlatformViewFactory(StandardMessageCodec.INSTANCE) {
    override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
        return LivePreviewView(context, viewId, args, messenger)
    }
}
